<template>
</template>

<script>
	import {
		getOpenId,
		wxCheckUserAndLogin
	} from "@/utils/wx_login"
	export default {
		data() {
			return {}
		},
		created() {
			this.checkUserAndLogin()
		},
		methods: {
			// 获取openid
			checkUserAndLogin() {
				let _this = this;
				wx.login({
					success(res) {
						if (res.code) {
							// console.log(res.code)
							getOpenId({
								js_code: res.code
							}).then(response => {
								// console.log(response)
								if (response.data.openid) {
									// 传给后台查看是否有这用户，没有则新建登录，有则直接登录
									wxCheckUserAndLogin({
										openid: response.data.openid
									}).then(res => {
										// console.log(res)
										uni.setStorageSync('openid', res.data.openid)
										uni.setStorageSync('userInfo', {
											name: res.data.name,
											phone: res.data.phone,
											avatar: res.data.avatar
										})
										uni.setStorageSync('token', {
											token: res.token,
											expiresAt: res.expiresAt
										})
										uni.$emit('alreadyLogin')
									}).catch(err => {
										console.log(err)
									})
								}
							}).catch(e => {
								console.log('error', e)
							})
						}
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
		}
	}
</script>

<style>
</style>